package com.novacloud.interceptor;

import com.alibaba.fastjson.JSON;
import com.novacloud.core.Result;
import com.novacloud.core.ResultCode;
import com.novacloud.exception.BaseException;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author <a href="mailto:huzhanjun@novacloud.com">huzj</a>
 * @version 1.0
 * @date 2017/9/25 9:54
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (true) {
            return true;
        } else {
            Result result = new Result();
            result.setCode(ResultCode.UNAUTHORIZED.code);
            result.setMessage(ResultCode.UNAUTHORIZED.message);
            writeJson(response, result);
            return false;
        }
    }

    private void writeJson(HttpServletResponse response, Object data) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print(JSON.toJSONString(data));
        out.flush();
        out.close();
    }
}
